/*购物车数组*/
let shopList = [];

function buy(bookId){
  //弹出遮罩
   $("shopDiv").style.visibility = "visible";
   $("shopDiv").style.width = document.documentElement.clientWidth+"px";
  $("shopDiv").style.height = document.documentElement.clientHeight+"px";

  //根据商品ID，得到购物车对象
  let bookObj = shopList.find(n => n.book.id == bookId);
  if(bookObj == null){//购物车中不存在该商品，在购物车中添加购物对象
     //从商品数组中查询该商品
      bookObj = bookArray.find(n => n.id == bookId);
      //创建购物车对象
      var shopObj = {book:bookObj,num:1};
      //在购物车中添加元素
      shopList.push(shopObj);
  }
  else{//购物车中有该商品，数量加一
     bookObj.num ++;
  }
  showShopInfo();
}

/**
 * 显示购物车信息
 */
function showShopInfo(){
   let str = "";
   let total = 0;
  shopList.forEach(n =>{
      str += `<tr><td>${n.book.name}</td><td>${n.book.price}</td>
            <td><input type="number" value="${n.num}" onblur="changeNum(this,${n.book.id})"></td>
            <td>${n.book.price * n.num}</td>
            <td><input type="button" value="移除商品" onclick="removeBook(${n.book.id})"></td></tr>`;
      total += n.book.price * n.num;
  })
  $("shopData").innerHTML = str;
  $("totalSpan").innerHTML = total;
}

/**
 * 移除购物车商品
 * @param bookId 书籍ID
 */
function removeBook(bookId){
  //查找商品在购物车中下标
    let index = shopList.findIndex(n => n.book.id == bookId);
    //从数组中删除元素
    shopList.splice(index,1);
    showShopInfo();
}

/**
 * 修改商品购买数量
 * @param txtObj 数量文本框
 * @param bookId 购买商品ID
 */
function changeNum(txtObj,bookId){
    if(txtObj.value.length == 0 || txtObj.value < 1){
      txtObj.value = 1;
    }
    //根据书籍ID，找到购物车对象
    let shopObj = shopList.find(n => n.book.id == bookId);
    //修改数量
    shopObj.num = parseInt(txtObj.value);
    showShopInfo();
}
